const { query, transaction } = require('../database/connection');

class Vehicle {
  /**
   * 根据车辆ID查找车辆
   * @param {string} vehicleId 车辆ID
   * @returns {Object|null} 车辆信息
   */
  static async findByVehicleId(vehicleId) {
    try {
      const results = await query(
        'SELECT * FROM vehicles WHERE vehicle_id = ? LIMIT 1',
        [vehicleId]
      );
      return results.length > 0 ? results[0] : null;
    } catch (error) {
      console.error('查找车辆失败:', error);
      throw error;
    }
  }

  /**
   * 根据用户ID查找车辆列表
   * @param {number} userId 用户ID
   * @returns {Array} 车辆列表
   */
  static async findByUserId(userId) {
    try {
      return await query(
        'SELECT * FROM vehicles WHERE user_id = ? AND status = "active" ORDER BY updated_at DESC',
        [userId]
      );
    } catch (error) {
      console.error('查找用户车辆失败:', error);
      throw error;
    }
  }

  /**
   * 创建或更新车辆信息
   * @param {Object} vehicleData 车辆数据
   * @returns {Object} 操作结果
   */
  static async upsert(vehicleData) {
    try {
      // 保底：user_id 为空时使用 NULL（不会触发外键约束），不要使用 0
      const hasUserId = !(vehicleData.user_id === undefined || vehicleData.user_id === null);
      const existing = await this.findByVehicleId(vehicleData.vehicle_id);
      
      if (existing) {
        // 更新现有车辆
        const nextStatus = (vehicleData.status === undefined) ? existing.status : vehicleData.status;
        const nextUserId = hasUserId ? vehicleData.user_id : existing.user_id;
        await query(
          `UPDATE vehicles SET 
          user_id = ?, vin = ?, model = ?, brand = ?, series = ?, color = ?, 
          year = ?, mileage = ?, battery_level = ?, charging_status = ?,
          location_lat = ?, location_lng = ?, status = ?, updated_at = NOW()
          WHERE vehicle_id = ?`,
          [
            nextUserId, vehicleData.vin, vehicleData.model,
            vehicleData.brand, vehicleData.series, vehicleData.color,
            vehicleData.year, vehicleData.mileage, vehicleData.battery_level,
            vehicleData.charging_status, vehicleData.location_lat,
            vehicleData.location_lng, nextStatus,
            vehicleData.vehicle_id
          ]
        );
        return { action: 'updated', vehicleId: vehicleData.vehicle_id };
      } else {
        // 创建新车辆
        if (vehicleData.status === undefined) {
          // 不写入 status 列，使用数据库默认值（兼容 INT 或 VARCHAR）
          await query(
            `INSERT INTO vehicles 
            (vehicle_id, user_id, vin, model, brand, series, color, year, 
             mileage, battery_level, charging_status, location_lat, location_lng)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
              vehicleData.vehicle_id, hasUserId ? vehicleData.user_id : null, vehicleData.vin,
              vehicleData.model, vehicleData.brand, vehicleData.series,
              vehicleData.color, vehicleData.year, vehicleData.mileage,
              vehicleData.battery_level, vehicleData.charging_status,
              vehicleData.location_lat, vehicleData.location_lng
            ]
          );
        } else {
          // 显式写入 status（由调用方保证与库类型一致）
          await query(
            `INSERT INTO vehicles 
            (vehicle_id, user_id, vin, model, brand, series, color, year, 
             mileage, battery_level, charging_status, location_lat, location_lng, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
              vehicleData.vehicle_id, hasUserId ? vehicleData.user_id : null, vehicleData.vin,
              vehicleData.model, vehicleData.brand, vehicleData.series,
              vehicleData.color, vehicleData.year, vehicleData.mileage,
              vehicleData.battery_level, vehicleData.charging_status,
              vehicleData.location_lat, vehicleData.location_lng,
              vehicleData.status
            ]
          );
        }
        return { action: 'created', vehicleId: vehicleData.vehicle_id };
      }
    } catch (error) {
      console.error('车辆信息保存失败:', error);
      throw error;
    }
  }

  /**
   * 批量同步车辆数据
   * @param {Array} vehiclesData 车辆数据数组
   * @returns {Object} 同步结果统计
   */
  static async batchSync(vehiclesData) {
    try {
      return await transaction(async (connection) => {
        let created = 0;
        let updated = 0;
        let errors = 0;

        for (const vehicleData of vehiclesData) {
          try {
            const result = await this.upsert(vehicleData);
            if (result.action === 'created') {
              created++;
            } else {
              updated++;
            }
          } catch (error) {
            console.error(`车辆 ${vehicleData.vehicle_id} 同步失败:`, error);
            errors++;
          }
        }

        return { created, updated, errors, total: vehiclesData.length };
      });
    } catch (error) {
      console.error('批量同步车辆失败:', error);
      throw error;
    }
  }

  /**
   * 更新车辆自定义图片
   * @param {string} vehicleId 车辆ID
   * @param {string} customImage 自定义图片路径
   * @returns {boolean} 更新结果
   */
  static async updateCustomImage(vehicleId, customImage) {
    try {
      const result = await query(
        'UPDATE vehicles SET custom_image = ?, updated_at = NOW() WHERE vehicle_id = ?',
        [customImage, vehicleId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新车辆自定义图片失败:', error);
      throw error;
    }
  }

  /**
   * 删除车辆（软删除）
   * @param {string} vehicleId 车辆ID
   * @returns {boolean} 删除结果
   */
  static async softDelete(vehicleId) {
    try {
      const result = await query(
        'UPDATE vehicles SET status = "deleted", updated_at = NOW() WHERE vehicle_id = ?',
        [vehicleId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除车辆失败:', error);
      throw error;
    }
  }
}

module.exports = Vehicle;
